<template>
  <div class="vip-list-add views-container">
    <choose-files ref="chooseFiles" :config="chooseFilesConfig" :changeEvt="uploadFileChange"></choose-files>
    <choose-ueditor-source ref="chooseUeditorSource" :changeEvt="chooseUeditorSourceChange" :typeT='typeT'></choose-ueditor-source>
    <el-dialog @close="searchText = '';" :visible.sync="dialogVisibleImg" width="35%" custom-class="reset-pwd wlm-form-dialog dialog-table">
      <div class="wlm-form">
        <div class="wlm-form-header wlm-dialog-fixheader">
          <span class="wlm-dialog-inlenr">搜索</span>
        </div>
        <div class="wlm-form-content">
          <div class="wlm-dialog-main">
            <div class="wlm-dialog-content">
              <el-form ref="user" :model="formFormatData.formData" :rules="formFormatData.rules" size="small" label-width="120px" class="retail-form" label-position="right">
                <el-form-item label="搜索内容">
                  <el-input maxlength="50" v-model="searchText" placeholder=""></el-input>
                </el-form-item>
              </el-form>
            </div>
          </div>
        </div>
      </div>
      <footer class="flex-row flex-align-c flex-justify-c wlm-dialog-fixfooter">
        <el-button size="small" @click="saveSearchText" type="primary">保存</el-button>
      </footer>
    </el-dialog>
    <el-dialog @close="scopeKeyName = '';scopeTextarea='';" :visible.sync="dialogTableVisible" custom-class="reset-pwd wlm-form-dialog dialog-table">
      <div class="wlm-form" v-if="dialogTableVisible">
        <div class="wlm-form-header wlm-dialog-fixheader">
          <span class="wlm-dialog-inlenr">添加文字</span>
        </div>
        <div class="el-card box-card is-always-shadow" v-if="showModel == 'reply'">
          <div class="el-card__body">
            <p>可用变量：</p>
            <p><span class="pointer" @click="handleClipboard('[$name]',$event)">[$name]</span>：微信昵称</p>
            <p><span class="pointer" @click="handleClipboard('[$time]',$event)">[$time]</span>：时间</p>
          </div>
        </div>
        <div class="el-card box-card is-always-shadow" v-if="showModel == 'reply'">
          <div class="el-card__body">
            <p>可填入文本信息（替换页面链接地址、小程序链接地址请去“平台=》页面链接”复制）</p>
            <p>页面链接：&lt;a href="替换页面链接地址"&gt;描述文字~&lt;/a&gt;</p>
            <p>小程序链接：&lt;a href="替换页面链接地址（必填）" data-miniprogram-appid="替换小程序appid" data-miniprogram-path="替换小程序链接地址"&gt;描述文字~&lt;/a&gt;</p>
          </div>
        </div>
        <el-scrollbar wrap-class="scrollbar-wrapper">
          <div class="wlm-form-content">
            <div class="wlm-dialog-main" style="padding:0;">
              <div class="wlm-dialog-content">
                <el-form :model="formFormatData.formData" :rules="formFormatData.rules" size="small" label-width="120px" class="retail-form" label-position="right">
                  <template v-if="showModel == 'keywords'">
                    <el-form-item label="触发关键字">
                      <el-radio-group style="margin-top:10px;" v-model="scopeModule" class="flex-row mar-15">
                        <el-radio label="1">精准触发</el-radio>
                        <el-radio label="2">包含关键字触发</el-radio>
                      </el-radio-group>
                    </el-form-item>
                    <el-form-item label="">
                      <el-input v-model="scopeKeyName">
                      </el-input>
                      <div v-show="formFormatData.formData.module!='search'" class="form-help">多个关键字请使用逗号隔开，如天气，今日天气</div>
                    </el-form-item>
                  </template>
                  <template v-if="showModel == 'reply'">
                    <el-form-item label="" label-width="0">
                      <el-input style="width:100%" type="textarea" :rows="8" :autosize="{ minRows: 4, maxRows: 8}" v-model="scopeTextarea"></el-input>
                    </el-form-item>
                  </template>
                </el-form>
              </div>
            </div>
          </div>
        </el-scrollbar>
      </div>
      <footer class="flex-row flex-align-c flex-justify-c wlm-dialog-fixfooter">
        <el-button size="small" type="primary" @click="addKeyWords">确定</el-button>
      </footer>
    </el-dialog>
    <div class="wlm-form">
      <div class="wlm-form-header">{{`${!!formFormatData.api['editForm']['params']['id']?'编辑':'添加'}自动回复`}}</div>
      <div class="wlm-form-content">
        <el-form :ref="formFormatData.key" :model="formFormatData.formData" :rules="formFormatData.rules" size="small" label-width="120px" class="retail-form" label-position="right">
          <el-form-item label="规则名称" prop="rulename">
            <el-input v-model.trim="formFormatData.formData.rulename">
            </el-input>
            <div class="form-help">您可以给这组触发关键字规则起一个名字, 方便下次修改和查看.</div>
          </el-form-item>
          <el-form-item label="回复类型">
            <el-radio-group v-model="formFormatData.formData.module" @change="moduleChange" class="wlm-form-group">
              <el-radio label="reply">关键字自动回复</el-radio>
              <el-radio label="first">首次关注回复</el-radio>
              <el-radio label="default">默认回复</el-radio>
              <el-radio label="search">搜索回复</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="添加关键字" prop="keywords" v-if="formFormatData.formData.module == 'reply'||formFormatData.formData.module == 'search'">
            <el-table :ref="tableFormatData.reply.key" :data="formFormatData.formData.keywords" style="width: 80%;margin-top: 10px;">
              <el-table-column width="60">
              </el-table-column>
              <el-table-column prop="date" label="关键字" header-align="left" align="left">
                <template slot-scope="scope">
                  <span>{{scope.row.content}}</span>
                  <!-- <el-input style="width: auto;" v-model.trim="scope.row.keywords" placeholder="请输入参数名称"></el-input> -->
                </template>
              </el-table-column>
              <el-table-column prop="name" label="触发类型" align="left">
                <template slot-scope="scope">
                  <span>{{modelMap[`${scope.row.type}`]}}</span>
                  <!-- <el-input style="width: auto;" v-model.trim="scope.row.model" placeholder="请输入参数值"></el-input> -->
                </template>
              </el-table-column>
              <el-table-column prop="address" label="操作" header-align="left" align="left">
                <template slot-scope="scope">
                  <div class="operation-group">
                    <el-button class="wlm-text" type="text" @click="delParameter(scope.$index)">删除</el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>
            <div class="add-keys-btn" @click="showModel == 'reply';dialogTableVisible = true;showModel = 'keywords';" style="display: block;text-align: center;border: 1px dashed #e8e9eb;background: #fff;margin-top:20px;margin-bottom:5px;margin-right: 20%;cursor: pointer;">
              <p class="flex-row flex-align-c flex-justify-c"><span style="font-size:24px;">+</span>&nbsp;&nbsp;&nbsp;<span>添加关键字</span></p>
            </div>
          </el-form-item>
          <el-form-item label="回复内容" prop="reply" v-if="formFormatData.formData.module != 'search'">
            <el-row style="border-top:1px solid #e8e9eb;padding:0 0px 15px;margin-top: 15px;width:80%;">
              <el-col :span="24">
                <div class="reply-list">
                  <!-- child begin-->
                  <div v-for="(childItem, childIndex) in formFormatData.formData.reply" :key="childIndex">
                    <div class="mar-line" v-if="childItem.type == 'basic'">
                      <el-form-item class="wlm-error-deep" label="" style="margin-top: 20px;margin-bottom:20px;" :prop="'reply.' + childIndex + '.content'" :rules="{required: true, message: '请输入回复内容', trigger: 'change'}">
                        <el-input style="width:40%" type="textarea" :rows="8" :autosize="{ minRows: 4, maxRows: 8}" v-model.trim="childItem.content"></el-input>
                      </el-form-item>
                      <div class="edit-btns flex-row flex-align-c flex-justify-b">
                        <el-button type="text" @click="formFormatData.formData.reply.splice(childIndex,1)">删除</el-button>
                      </div>
                    </div>
                    <!-- <div class="mar-line" v-if="childItem.type != 'basic'">
                              <el-form-item class="wlm-error-deep" label="" style="margin-top: 20px;margin-bottom:20px;" :prop="'reply.' + childIndex + '.content'" :rules="{required: true, message: '请输入回复内容', trigger: 'change'}">
                                商品关键词：<el-input v-model.trim="childItem.content"></el-input>
                              </el-form-item>
                              <div class="edit-btns flex-row flex-align-c flex-justify-b">
                                <el-button type="text" @click="formFormatData.formData.reply.splice(childIndex,1)">删除</el-button>
                              </div>
                            </div> -->
                    <!-- news begin-->
                    <div v-if="childItem.type == 'news'" class="news-media mar-line">

                      <div class="desc">
                        <div class="media-content">
                          <div class="appmsgSendedItem">
                            <div class="title-wrp">
                              <span class="icon img-center" :style="{'background-image':`url(${childItem.content['items'][0]['thumb_url']})`}"></span>
                              <span class="title">[图文消息]{{childItem.content['items'][0]['title']}}<span class="color-red">（多条图文只显示一条,不影响实际回复效果）</span></span>
                            </div>
                            <p class="desc">{{childItem.content['items'][0]['digest']}}</p>
                          </div>
                        </div>
                      </div>

                      <div class="edit-btns flex-row flex-align-c flex-justify-b">
                        <el-button type="text" @click="editReply(childItem.type, childItem)">编辑</el-button>
                        <el-button type="text" @click="formFormatData.formData.reply.splice(childIndex,1)">删除</el-button>
                      </div>
                    </div>
                    <!-- news end-->
                    <!-- 图文链接 -->
                    <div v-if="childItem.type == 'newsText'" class="news-media mar-line" style="border-bottom: 1px solid rgb(232, 233, 235);">
                      <div v-for="(newsTextItem,newsTextIndex) in childItem.content" :key="newsTextIndex" :style="newsTextIndex!=childItem.content.length-1?'border-bottom: 1px dashed rgb(232, 233, 235);':''">
                        <div>
                          <span>{{newsTextItem.title}}</span>
                          <span>{{newsTextItem.create_time}}</span>
                        </div>

                        <el-button type="text" @click="jump(childItem.type,newsTextItem.imgtext_id)">编辑</el-button>
                        <el-button type="text" @click="delData(childItem.content,newsTextIndex,childIndex)">删除</el-button>

                      </div>

                    </div>

                    <!-- 小程序卡片 -->
                    <div v-if="childItem.type == 'sappCard'" style="border-bottom: 1px solid rgb(232, 233, 235);">

                      <div v-for="(newsTextItem,newsTextIndex) in childItem.content" :key="newsTextIndex" :style="newsTextIndex!=childItem.content.length-1?'border-bottom: 1px dashed rgb(232, 233, 235);':''">
                        <div>
                          <span>卡片名称：{{newsTextItem.title}}</span>
                          <span>内容：{{newsTextItem.text}}</span>
                          <span>appId：{{newsTextItem.appid}}</span>
                        </div>
                         <el-button type="text" @click="jump(childItem.type,newsTextItem.sapp_card_id)">编辑</el-button>
                        <el-button type="text" @click="delData(childItem.content,newsTextIndex,childIndex)">删除</el-button>
                      </div>
                    </div>
                    <!-- images begin -->
                    <div v-if="childItem.type == 'images'" class="news-media mar-line">
                      <div class="desc">
                        <div class="media-content">
                          <div class="appmsgSendedItem">
                            <div class="title-wrp">
                              <span class="icon img-center" v-if="childItem.content" :style="{'background-image':`url(${childItem.content['file_path']})`}"></span>
                              <span class="title">[图片]</span>
                            </div>
                          </div>
                        </div>
                      </div>
                      <div class="edit-btns flex-row flex-align-c flex-justify-b">
                        <el-button type="text" @click="formFormatData.formData.reply.splice(childIndex,1)">删除</el-button>
                      </div>
                    </div>
                    <!-- images end -->
                    <!-- music begin -->
                    <div v-if="childItem.type == 'music'" class="news-media mar-line">
                      <div class="desc">
                        <div class="media-content">
                          <div class="appmsgSendedItem audio">
                            <div class="title-wrp">
                              <span class="icon">
                                <audio v-if="childItem.content['file_type'] == 'audio'" class="audio-box pos-center" preload="preload" :src="childItem.content['file_path']" controls="controls"></audio>
                              </span>
                              <span class="title">[音频]</span>
                            </div>
                          </div>
                        </div>
                      </div>
                      <div class="edit-btns flex-row flex-align-c flex-justify-b">
                        <el-button type="text" @click="formFormatData.formData.reply.splice(childIndex,1)">删除</el-button>
                      </div>
                    </div>
                    <!-- music end -->
                    <!-- vedio begin -->
                    <div v-if="childItem.type == 'video'" class="news-media mar-line">
                      <div class="desc">
                        <div class="media-content">
                          <div class="appmsgSendedItem video">
                            <div class="title-wrp">
                              <span class="icon">
                                <video v-if="childItem.content['file_type'] == 'video'" class="video-box pos-center" :src="childItem.content['file_path']" controls="controls" />
                              </span>
                              <span class="title">[视频]</span>
                            </div>
                          </div>
                        </div>
                      </div>
                      <div class="edit-btns flex-row flex-align-c flex-justify-b">
                        <el-button type="text" @click="formFormatData.formData.reply.splice(childIndex,1)">删除</el-button>
                      </div>
                    </div>
                    <!-- vedio end -->
                  </div>
                  <!-- child end-->
                </div>
              </el-col>
            </el-row>
            <el-row v-for="(replyItem, replyIndex) in replyList" :key="replyIndex" type="flex" style="padding:30px 0 15px;width:80%;">
              <el-col v-for="(item, index) in replyItem.content" :key="index" :span="4">
                <div class="flex-row flex-align-c flex-justify-c reply-item" @click="settingReply(item.key)">
                  <img :src="getPath(`${item.path}`)">
                  <span style="margin-left:10px;">{{item.name}}</span>
                </div>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div v-cloak class="wlm-fixed-btn flex-row flex-align-c flex-justify-c">
      <el-button size="small" @click="formFormatSubmit({ router: { type: 'replace', path: '/channel/weChatReplyChannelList', code: 1 }})" type="primary">保存</el-button>
      <router-link tag="span" to="/channel/weChatReplyChannelList">
        <el-button size="small">返回</el-button>
      </router-link>
    </div>
  </div>
</template>

<script>
import ChooseFiles from '@/components/ChooseFiles/index'
import ChooseUeditorSource from '@/components/ChooseUeditorSource/index'
import clipboard from '@/utils/clipboard'
import {
  addReply,
  getReplyDetail,
  upload2WechatByFileID
} from '@/api/channel'
import mixins from '@/mixins/mixins'
export default {
  mixins: [mixins.getters('Form')],
  name: 'WeChatReplyChannelListAdd',
  components: {
    ChooseFiles,
    ChooseUeditorSource
  },
  computed: {
    getPath() {
      return function(path) {
        return (path.includes('https://') || path.includes('http://')) ? `${path}` : require(`@/assets/channel_wechat/${path}`)
      }
    }
  },
  directives: {

  },
  created() {

  },
  data() {
    var checkArray = (rule, value, callback) => {
      const { message } = rule
      if (!Array.isArray(value) || (Array.isArray(value) && value.length === 0)) {
        return callback(new Error(`${message}！~`))
      } else {
        callback()
      }
    }
    return {
      typeT: 'news',
      searchText: '',
      dialogVisibleImg: false,
      chooseFilesConfig: {
        type: ['image'],
        model: 'normal',
        initList: [],
        file_type: 'image',
        uploadConfig: {
          params: {
            mode: 'perm'
          }
        }
      },
      modelMap: {
        '1': '精准触发',
        '2': '包含关键字触发'
      },
      scopeKeyName: '',
      scopeModule: '1',
      scopeTextarea: '',
      showModel: 'keywords',
      dialogTableVisible: false,
      replyList: [{
        content: [{
          key: 'appmsg',
          path: 'appmsg-icon.png',
          name: '图文'
        },
        {
          key: 'text',
          path: 'text-icon.png',
          name: '文字'
        },
        {
          key: 'image',
          path: 'image-icon.png',
          name: '微信图片'
        },
        {
          key: 'music',
          path: 'music-icon.png',
          name: '音频'
        },
        {
          key: 'vedio',
          path: 'vedio-icon.png',
          name: '视频'
        },
        {
          key: 'card',
          path: 'text-icon.png',
          name: '小程序卡片'
        }
        ]
      }],
      tableFormatData: {
        current: 'weChatReplyAdd',
        reply: {
          key: 'weChatReplyAdd'
        }
      },
      formFormatData: {
        key: 'userForm',
        model: {
          noCreateEdit: false,
          bindDialog: 'dialogTableVisible'
        },
        api: {
          editForm: {
            api: getReplyDetail,
            params: {
              id: ''
            }
          },
          submitForm: addReply
        },
        formData: {
          rulename: '',
          module: 'reply',
          keywords: [],
          reply: [
            // basic: '',
            // news: {},
            // images: {},
            // music: {},
            // video: {}
          ]
        },
        rules: {
          rulename: [{
            message: '请输入规则名称',
            required: true,
            trigger: 'change'
          }],
          keywords: [{
            message: '请添加关键字',
            required: true,
            validator: checkArray,
            trigger: 'change'
          }],
          reply: [{
            message: '请添加回复内容',
            required: true,
            validator: checkArray,
            trigger: 'change'
          }]
        }
      }
    }
  },
  methods: {
    jump(type, id) {
      type == 'newsText' && this.$router.push({ path: '/application/imgtxtEdit', query: { imgtext_id: id } })
      type == 'sappCard' && this.$router.push({ path: '/application/wechartCardAdd', query: { id: id } })
    },
    delData(item, index, pIndex) {
      item.splice(index, 1)
      item.length == 0 && this.formFormatData.formData.reply.splice(pIndex, 1)
    },
    upload2WechatByFile(currentRow) {
      upload2WechatByFileID({ ids: currentRow, mode: 'perm' }).then(res => {
        this.getTableList()
      })
    },
    handleClipboard(text, event) {
      clipboard(text, event)
    },
    uploadtoggle(type, params = {}) {
      if (type) {
        if (['image', 'video', 'audio'].includes(type)) {
          this.chooseFilesConfig.file_type = type
        }
        this.$refs.chooseFiles.toggle()
      }
    },
    uploadFileChange(files) {
      const { currentRow, displayData, type: [file_type] } = files
      switch (file_type) {
        case 'image':
          this.formFormatData.formData.reply.push({ type: 'images', content: displayData[displayData.length - 1] })
          break
        case 'video':
          this.formFormatData.formData.reply.push({ type: 'video', content: displayData[displayData.length - 1] })
          break
        case 'audio':
          this.formFormatData.formData.reply.push({ type: 'music', content: displayData[displayData.length - 1] })
          break
      }
      this.upload2WechatByFile(currentRow)
    },
    saveSearchText() {
      this.formFormatData.formData.reply.push({ type: 'search', content: this.searchText })
      console.log(this.formFormatData.formData.reply, 'rep')
      this.dialogVisibleImg = false
    },
    moduleChange() {
      // this.formFormatData.formData.keywords = []
      // if (this.formFormatData.formData.module === 'search') {
      //   this.dialogVisibleImg = true
      // }
    },
    addKeyWords() {
      const keyName = this.scopeKeyName
      const textarea = this.scopeTextarea
      const isModel = this.showModel
      const checkMsg = {
        value: isModel === 'keywords' ? keyName : textarea,
        error: isModel === 'keywords' ? '关键词不可为空~!' : '回复内容不可为空~!'
      }
      if (!checkMsg.value) {
        this.$message.error(checkMsg.error)
      } else {
        if (isModel === 'keywords') {
          this.formFormatData.formData.keywords.push({
            type: this.scopeModule,
            content: keyName
          })
        } else {
          this.formFormatData.formData.reply.push({ type: 'basic', content: checkMsg.value })
        }

        this.scopeKeyName = ''
        this.scopeModule = '1'
        this.scopeTextarea = ''
        this.dialogTableVisible = false
      }
    },
    delParameter($index) {
      this.formFormatData.formData.keywords.splice($index, 1)
    },
    editReply(key, value) {
      const { content: { items: [{ id }] } } = value
      switch (key) {
        case 'news':
          this.$router.push({ path: '/channel/weChatPublicUeditorSourceAdd', query: { attach_id: id } })
          break
      }
    },
    settingReply(key) {
      console.log(key)
      switch (key) {
        case 'appmsg':
          this.$refs.chooseUeditorSource.toggle()
          this.typeT = 'news'
          break
        case 'text':
          this.showModel = 'reply'
          this.dialogTableVisible = true
          break
        case 'image':
          this.uploadtoggle('image')
          break
        case 'music':
          this.uploadtoggle('audio')
          break
        case 'vedio':
          this.uploadtoggle('video')
          break
        case 'card':
          this.$refs.chooseUeditorSource.toggle()
          this.typeT = 'card'
          break
        // case 'search':
        //   this.uploadtoggle('search')
        //   break
      }
    },
    chooseUeditorSourceChange(files) {
      console.log(files, '+++++++++++++++++++++++')
      const { displayData, type: type1 = '' } = files
      this.type = type1
      type1 == 'newText' ? this.formFormatData.formData.reply.push({ type: 'newsText', content: displayData }) : type1 == 'card' ? this.formFormatData.formData.reply.push({ type: 'sappCard', content: displayData }) : (this.formFormatData.formData.reply.push({ type: 'news', content: displayData[displayData.length - 1] }))
    }
  }
}
</script>

<style lang="scss" scoped>
.reply-item {
  cursor: pointer;
}

.box-card {
  background-color: #f5f5f5;
  font-size: 14px;
  margin: 20px;
  color: #606266;
}

.reply-list {
  .mar-line {
    position: relative;
    border-bottom: 1px solid rgb(232, 233, 235);
  }

  .edit-btns {
    position: absolute;
    right: 20px;
    top: 0;
  }

  .news-media {
    .desc {
      padding: 15px 0;
      line-height: normal;

      .appmsgSendedItem {
        position: relative;
        padding-left: 90px;
        min-height: 80px;

        .title-wrp {
          .title {
            display: block;
            font-weight: 400;
            font-style: normal;
            width: auto;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            word-wrap: normal;

            .color-red {
              color: #cf1010 !important;
            }
          }

          .icon {
            position: absolute;
            left: 0;
            width: 80px;
            height: 80px;
            vertical-align: middle;
            display: inline-block;
            background-color: #d7d8da !important;
          }
        }

        &.video,
        &.audio {
          padding-left: 160px;

          .icon {
            width: 150px;

            video {
              height: 100%;
              width: 100%;
            }

            audio {
              width: 100%;
            }
          }
        }
      }
    }
  }
}
</style>
